import com.mind.jenkins.pipeline.utils.BuildConfig
import java.time.LocalDate

def call() {
    // properties([
            // parameters([
                    // string(defaultValue: '', description: '', name: 'COMMIT', trim: false),
                    // string(defaultValue: 'pre-release', description: '', name: 'BRANCH', trim: false),
                    // choice(choices: ['EVOFLOW-PRE', 'EVOFLOW-PROD', 'EVOFLOW-DEV'], description: '选择发布环境,默认pre', name: 'ENV'),
                    // choice(choices: ['pre-release', 'release'], description: '选择分支,默认pre-release', name: 'BRANCH'),
            // ])
    // ])
               

    dockerNode.golangBuildDocker {
        BuildConfig buildConfig
        boolean isSuccess = false
        def causes = currentBuild.getBuildCauses()
        def buildUser = causes[0]?.userId ?: 'Unknown'
        echo "Build User: ${buildUser}"
        try {


            if ("${ENV}" == "EVOFLOW-PROD"){
                stage('部署生产之前二次确认') {
                    input(message: "确定发布环境 ${ENV} 的 ${BRANCH}分支？", ok: 'Continue')
                }
            }
            environment { 
                GOPROXY = "https://goproxy.io,direct"
            }
            stage('准备拉取代码') {
                //checkout scm
                checkout([
                        $class           : 'GitSCM',
                        branches         : [[name: BRANCH]],
                        userRemoteConfigs: scm.userRemoteConfigs
                ])
            }

   

            

            echo "当前发布环境：${ENV}, 当前发布分支：${BRANCH},serverName: ${serverName}"

            // String appname = jobUtil.getAppNameFromJob()
            // echo "当前服务名：${appname}"

            Object commitInfo = jobUtil.getCommitInfo()

            String imageAddr = jobUtil.getImageAdd(ENV)

            String imageName
            String coskey
            String[] servicesList
            sName = "${serverName}"
            servicesList = sName.tokenize('|')

            String goVersion

            if (params.golangVersion == null){
                goVersion = "golang-v1.17"
            }else{
                goVersion = params.golangVersion
            }



            stage('模块初始化') {
                // 将依赖包缓存到名为 'go-deps' 的stash中
                stash(name: 'go-deps', includes: 'go.sum,go.mod')
                // def gitCredentials = credentials('1355d42a-0980-4226-ab32-3808ae4dd84c')
                // withCredentials([usernamePassword(credentialsId: '1355d42a-0980-4226-ab32-3808ae4dd84c', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD')]) {
                // 切换golang环境
                def root = tool name: "${goVersion}", type: 'go'        
                withEnv(["GOROOT=${root}", "PATH+GO=${root}/bin"]){
                     // 初始化
                    sh 'git submodule deinit -f cmd/Open-IM-SDK-Core'
                    sh 'git submodule init'
                    withCredentials([sshUserPrivateKey(credentialsId: '1355d42a-0980-4226-ab32-3808ae4dd84c', keyFileVariable: 'KeyFile', passphraseVariable: '', usernameVariable: 'c')]) {
                        echo " ${c}"
                        // sh 'git submodule update --remote'
                        // sh "git submodule update --remote --init --recursive"
                        sh "git submodule update --remote"
                        // sh "GIT_SSH_COMMAND='ssh -i ${KeyFile}' git submodule update --remote"

                    }
                    

                    sh 'cd cmd/Open-IM-SDK-Core/'
                    sh "git reset --hard origin/${BRANCH}"
                    def currentPath = pwd()
                    echo "PWD:${currentPath}"
                    
                    sh 'cd ./script && ./build_jenkins_all_service.sh'
                    echo "code build success"
                    echo "${servicesList}"
                    // 创建一个并行任务列表
                    def parallelMoveTasks = [:]
                    
                    for (int i = 0; i < servicesList.size(); i++){
                        def appname = servicesList[i]
                        parallelMoveTasks[appname] = {
                            dir("./deploy_k8s"){
                                    sh "mv ../bin/open_im_${appname} ./${appname}/"
                                    sh "ls ./${appname}/"
                                }
                        }
                    }
                    parallel parallelMoveTasks

                    echo "move success"
                }

                   
                
            }


            stage('批量构建镜像') {        
                parallel 'docker': {
                    echo "Build docker image..."
                    // 在这里执行构建步骤，可以从缓存中unstash依赖包
                    unstash('go-deps')
                    // 创建一个并行任务列表
                    // def parallelTasks = [:]

                    for (int i = 0; i < servicesList.size(); i++){
                        def appn = servicesList[i]
                        def currentDate = LocalDate.now()
                        // parallelTasks[appn] = {
                            def appname = appn.replaceAll("_","-")
                            stage("开始构建服务${appn}"){
                                echo "build ${appn}"
                                dir("./deploy_k8s/${appn}"){
                                    imageName = "${imageAddr}/${appname}:${currentDate}_${env.BUILD_NUMBER}"
                                    dockerfile = "./${appn}.Dockerfile"
                                    jobUtil.buildDockerImage(dockerfile, appname, "golang", imageName,"")
                                }
                                stage("应用部署${appname}") {
                                    echo "Build success, Now Callback Cd for ${appname}"
                                    def env = params.ENV
                                    def app = "mind-im-${appname}-server"
                                    def branch = params.BRANCH
                                    echo "appname: ${app} imageName: ${imageName}"
                                    jobUtil.createBananaBuild(app, "deploy", env, buildUser, coskey, imageName, commitInfo, branch)
                                    // imageNameMap[imageName]=appname   
                                    }
                                // stage("通知${appname}") {
                                //     echo "通知工作群...${appname}"
                                //     isSuccess = currentBuild.result == null || currentBuild.result == 'SUCCESS'
                                //     def branch = params.BRANCH
                                //     def env = params.ENV
                                //     notifyUtil.notifyApp(jobUtil.getRepoName(), branch, env, isSuccess, buildUser)
                                //     }
                                }
                        
                    }

                   
                    // 并行步骤
                    // parallel parallelTasks





                    
                  
                }, 'cos': {
                     echo "构建文件上传COS中..."
                }
            }

            // stage('单元测试') {
            //     echo "单元测试中...."
            // }

            // stage('质量检测') {
            //     echo "SonarScanner质量检查扫描中...."
            // }

            // stage('应用部署') {
                // echo "Build success, Now Callback Cd..."
                // def env = params.ENV
                // echo "image map: ${imageNameMap}"
                // for (entry in imageNameMap ){
                //     def image = entry.key
                //     def app = "mind-im-${entry.value}-server"
                //     def branch = params.BRANCH
                //     echo "appname: ${app} imageName: ${image}"
                //     jobUtil.createBananaBuild(app, "deploy", env, buildUser, coskey, image, commitInfo, branch)
                // }
            // }
        } finally {
            try {
                stage('通知') {
                    // echo "通知工作群..."
                    // isSuccess = currentBuild.result == null || currentBuild.result == 'SUCCESS'
                    // def branch = params.BRANCH
                    // def env = params.ENV
                    // notifyUtil.notifyApp(jobUtil.getRepoName(), branch, env, isSuccess, buildUser)
                }
                
            } catch (err) {
                echo err.getMessage()
            }
            // deleteDir()
        }
    }
}